package org.jwos.plugin.file.web;

import java.io.IOException;

import javax.jcr.LoginException;
import javax.jcr.RepositoryException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.jwos.plugin.file.jcr.util.RepositorySessionFactory;

public class RepositoryFilter implements Filter {	
	
	protected static Logger logger = Logger.getLogger(RepositoryFilter.class);

	public void init(FilterConfig config) throws ServletException {		
	}

	public void destroy() {
	}	

	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		
		logger.debug(req.getRequestURI()+" repository session login");
		
		try {
			RepositorySessionFactory.openSession("admin", "admin");
		} catch (LoginException e) {
			logger.error(req.getRequestURI()+" repository session login error: "+e.getLocalizedMessage());	
			e.printStackTrace();
		} catch (RepositoryException e) {
			logger.error(req.getRequestURI()+" repository session open error: "+e.getLocalizedMessage());
			e.printStackTrace();
		}
		
		chain.doFilter(request, response);
		
		RepositorySessionFactory.closeSession();
		logger.debug(req.getRequestURI()+" repository session logout");		
	}
	
}
